<template>
    <div class="textarea-box">
        <div class="textarea-item" v-if="file.query">
            <div class="Tools">
                <el-dropdown @command="queryHandle">
                    <el-button size="small" type="primary" icon="el-icon-s-tools" circle></el-button>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item command="format">格式化</el-dropdown-item>
                        <el-dropdown-item command="restore">还原</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </div>
            <div class="title">URL 参数</div>
            <textarea ref="query"></textarea>
        </div>
        <div class="textarea-item" v-if="file.body">
            <div class="Tools">
                <el-dropdown @command="bodyHandle">
                    <el-button size="small" type="primary" icon="el-icon-s-tools" circle></el-button>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item command="format">格式化</el-dropdown-item>
                        <el-dropdown-item command="restore">还原</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </div>
            <div class="title">Body 参数</div>
            <textarea ref="body"></textarea>
        </div>
    </div>
</template>

<script>
import format from './format'
const renderAnnotation = item => ' // ' + item.annotate + ' (' + item.type + ') ' + (item.checked ? '必填' : '') + '\n';
export default {
    props: ['file'],
    data() {
        return {
            queryOptions: {
                data: [],
                Schema: {},
            },
            bodyOptions: {
                data: [],
                Schema: {},
            },
        }
    },
    mounted() {
        if (this.file.query) {
            this.initQueryCodeMirror();
            this.initQuery();
            this.formatQueryJson();
        }
        if (this.file.body) {
            this.initBodyCodeMirror();
            // this.initBody();
            this.formatBodyJson();
        }
    },
    methods: {
        initQuery() {
            this.file.query.forEach(ele => {
                var _data = {};
                _data.key = ele.name;
                _data.type = ele.schema.type;
                _data.annotate = ele.description || '';
                _data.checked = !ele.nullable;
                this.queryOptions.data.push(_data);
                this.queryOptions.Schema[ele.name] = ele.schema;
            });
        },
        formatBodyJson() {
            for (const key in this.file.body) {
                const element = this.file.body[key];
                var _String = format.String(element, this.$bus.getFolder(this.file.parent).models);
                var str = this.beautify(_String);
                this.body.setValue(str);
            }
        },
        formatQueryJson() {
            var data = this.queryOptions.data;
            var _String = '{'
            for (let i = 0; i < data.length; i++) {
                var item = data[i];
                if (item.type == 'object') {
                    _String += (item.key + ': {},' + renderAnnotation(item));
                } else {
                    _String += ((item.key ? item.key : '\'\'') + ':' + '\'\',' + renderAnnotation(item));
                }
            };
            _String += '}'
            var str = this.beautify(_String);
            this.query.setValue(str);
        },
        queryHandle(code) {
            if (code == 'format') {
                this.formatJson('query');
            } else if (code == 'restore') {
                this.formatQueryJson();
            }
        },
        bodyHandle() {
            if (code == 'format') {
                this.formatJson('body');
            } else if (code == 'restore') {
                this.formatBodyJson();
            }
        },
        initQueryCodeMirror() {
            this.query = this.$CodeMirror.fromTextArea(this.$refs.query, {
                mode: 'text/javascript',
                indentWithTabs: true,
                smartIndent: false,
                lineNumbers: true,
                lineWrapping: true,
                foldGutter: true,
                matchBrackets: true,
                gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
                theme: 'mdn-like',
            });
            this.query.on('beforeChange', (instance, changeObj) => {
                if (changeObj.origin == '+input' && (changeObj.text == '\'' || changeObj.text == '\"')) {
                    var _str = this.query.getSelection();
                    if (_str.toString().length > 0) {
                        this.query.replaceSelection(_str + _str + changeObj.text);
                    };
                };
            });
        },
        initBodyCodeMirror() {
            this.body = this.$CodeMirror.fromTextArea(this.$refs.body, {
                mode: 'text/javascript',
                indentWithTabs: true,
                smartIndent: false,
                lineNumbers: true,
                lineWrapping: true,
                foldGutter: true,
                matchBrackets: true,
                gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
                theme: 'mdn-like',
            });
            this.body.on('beforeChange', (instance, changeObj) => {
                if (changeObj.origin == '+input' && (changeObj.text == '\'' || changeObj.text == '\"')) {
                    var _str = this.body.getSelection();
                    if (_str.toString().length > 0) {
                        this.body.replaceSelection(_str + _str + changeObj.text);
                    };
                };
            });
        },
        formatJson(type) {
            var str = this[type].getValue();
            str = this.beautify(str);
            this[type].setValue(str);
        },
        beautify(source) {
            function looks_like_html(source) {
                var trimmed = source.replace(/^[ \t\n\r]+/, '');
                return trimmed && (trimmed.substring(0, 1) === '<');
            };
            var output,
                opts = {
                    // brace_style : "expand"
                };
            opts.indent_char = ' ';
            opts.preserve_newlines = "-1";
            if (looks_like_html(source)) {
                output = html_beautify(source, opts);
            } else {
                output = js_beautify(source, opts);
            };
            return output;
        },
        getOptions() {
            var _data = {};
            this.file.query && (eval('_data.query = ' + this.query.getValue()));
            this.file.body && (eval('_data.body = ' + this.body.getValue()))
            return _data;
        }
    }
}
</script>

<style>
</style>